package com.example.formatter;

import org.springframework.stereotype.Service;
import java.io.*;

@Service
public class FormatService {

    public String format(String language, String code) {
        // 语言白名单校验
        String lang = language == null ? "" : language.toLowerCase();
        if (!("java".equals(lang) || "js".equals(lang) || "javascript".equals(lang))) {
            return "不支持的语言类型，只允许 java/js/javascript";
        }
        // 代码长度限制（2MB）
        if (code == null || code.length() > 2 * 1024 * 1024) {
            return "代码内容为空或超过2MB限制";
        }
        try {
            switch (lang) {
                case "java":
                    return runFormatter(new String[]{"java", "-jar", "/usr/local/bin/google-java-format.jar", "-"}, code);
                case "javascript":
                case "js":
                    return runFormatter(new String[]{"prettier", "--stdin-filepath", "temp.js"}, code);
                default:
                    return code; // 理论不会走到这里
            }
        } catch (Exception e) {
            return "格式化失败: " + e.getMessage();
        }
    }

    private String runFormatter(String[] command, String code) throws IOException, InterruptedException {
        ProcessBuilder builder = new ProcessBuilder(command);
        Process process = builder.start();
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()))) {
            writer.write(code);
            writer.flush();
        }
        StringBuilder output = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append('\n');
            }
        }
        process.waitFor();
        return output.toString();
    }
}